package com.ims.controller.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 捕获异常统一处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private final static String EXPTION_MSG_KEY = "message";

    @ExceptionHandler(CustomerException.class)
    public Map<String,String> customerExceptionHandler(CustomerException ex){
        Map<String,String> res = new HashMap<>();
        ex.printStackTrace();
        res.put("errCode",ex.getErrCode());
        res.put("errMsg",ex.getErrMsg());
        return res;
    }

    @ExceptionHandler(SQLException.class)
    public Map<String,String> sqlExceptionHandler(SQLException ex){
        Map<String,String> res = new HashMap<>();
        ex.printStackTrace();
        res.put("errorCode","3306");
        res.put("errorMsg",ex.getMessage());
        return res;
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAndReturnPage(HttpServletRequest request, HttpServletResponse response, Exception ex) {

        ModelAndView  mv = new ModelAndView("save_result") ;
        mv.addObject("msg", ex);


            return mv; //返回Exception.jsp页面

    }
}
